/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

dojo.provide("nanosn.widgets.crud._Editor");
dojo.require("dijit._Widget");
dojo.require("dijit._Templated");
dojo.require("dijit.form.Form");
dojo.require("dijit.form.TextBox");
dojo.declare("nanosn.widgets.crud._Editor", [dijit._Widget, dijit._Templated],
{
    // TODO
    widgetsInTemplate: true,
    templatePath: dojo.moduleUrl("nanosn.widgets.crud","templates/_Editor.html"),
    

    /**
     * TODO: CSS support
     * TODO: this is a DTL String
     */
    _fieldTemplate: "<tr><td><label for='{{ editor }}'>{{ label }}:</label></td><td><input class='{{ id }}' dojoType='{{ type }}' name='{{ editor }}' type='text' /></td></tr>",


    /**
     * this structure is similar to the structure of the layout of a DataGrid
     * Here is an example: [{name: "Id", field: "id"}]
     *   - Available options:
     *       - name (reqired)
     *          The label of the field.
     *       - field
     *          The name of the field in the store data
     *       - width
     *          The width of the column
     *       - editorType
     *          The type of editor. Allowable types are any of the dijit widgets
     *          TODOC: List all allowable types
     *       - options
     *           Used when editorType is FIXME: Select to name the allowable options
     *       - editable
     *           A boolean value that declares whether or not the cell is editable
     *       - formatter
     *           A JavaScript function that is called which returns the value
     *           to be shown in the cell. The value from the data store is
     *           passed as a parameter to the function. The returned value
     *           that is inserted into the page can be any legal HTML.
     *           It should not be a dijit Widget as that is not parsed.
     *       - get
     *           A JavaScript function that is called which returns the value
     *           to be shown in the cell. The function is passed two parameters.
     *           The first is the row index in the DataGrid. The second is the
     *           DataStore record/item. Given these two parameters, the function
     *           is expected to know what to return. It should not be a dijit
     *           Widget as that is not parsed. Care should be taken that the
     *           item parameter is not null. Tests have shown that the function
     *           may be called more often than it should be and this is
     *           highlighted with an item = null.
     *       - hidden
     *           This boolean property can be used to hide a column in the
     *           table. If its value is true the column is hidden. If false
     *           the column is displayed.
     *
     *           TODO: There should be more ... validator, required
     */

    container: null,
    
    postMixInProperties: function()
    {
        if(djConfig.isDebug)
        {
            console.log("postMixInProperties");
        }

    },

    buildRendering: function()
    {
        this.inherited(arguments);
        this._generateEditFields();
    },

    postCreate: function()
    {
        //This is typically the workhorse of a custom widget.
        //The widget has been rendered (but note that sub-widgets
        // in the containerNode have not!)

        //TODO: This is only testing
        if(djConfig.isDebug)
            console.log("postCreate");
        var inputCollection = dojo.query("." + this.id);
        
        if(djConfig.isDebug)
            console.log(inputCollection);

    },
    
    startup: function()
    {
        this.inherited(arguments);
        
        if(djConfig.isDebug)
            console.log("startup");
        
        var myThis = this;
        setTimeout(function ()
        {

            var inputCollection = dojo.query("." + myThis.id);
            inputCollection.forEach(function(inputElement)
            {
                elem = dijit.byId(inputElement.id);
                dojo.connect(inputElement, "onblur", this, this.inputOnBlur);
                dojo.connect(inputElement, "onfocus", this, this.inputOnFocus);
            }, myThis /*scope*/);

        }, 100);
    },

    tmpValue: null,
    inputOnFocus: function (e)
    {
        this.tmpValue = e.target.value;
        
    },
    inputOnBlur: function (e)
    {
        console.log("blur");
        console.log(e);
        if (this.tmpValue != e.target.value) 
        {
            console.log("Oh Value changed from: [" + this.tmpValue + "] to [" + e.target.value + "]");

            eval("this.container.item." + e.target.name + "='" + e.target.value + "'");
            eval("this.container.item." + e.target.name);
            this.container._store.setValue(this.container.item, e.target.name, e.target.value);

        }
    },

    _generateEditFields: function()
    {
        dojo.require("dojox.dtl");
        dojo.require("dojox.dtl.Context");

        var template = new dojox.dtl.Template(this._fieldTemplate);

        dojo.forEach(this.container._structure, function(item)
        {
            var context = new dojox.dtl.Context(
            {
                label: item.name,
                editor: item.field,
                id: this.id,
                type: "dijit.form.TextBox"
            });
            
            this.fields.innerHTML += template.render(context);
        }, this);
    },

    setItem: function (item)
    {
        //TODO: change the logic to be looping at a local array
        console.debug(item);
        this.container.item = item;

        inputCollection = dojo.query("." + this.id);
        inputCollection.forEach(function(inputElement)
        {
            try
            {
                if (inputElement.name)
                {
                    value = eval("item." + inputElement.name);
                    //Reset value just in case
                    inputElement.value = "";
                    if (value != undefined)
                    {
                        inputElement.value = value;
                    }
                    else
                    {
                        error = new Error();
                        error.message = "DEBUG: nanosn.tracfaces.ui.DataEditor._fill_editor_data: " +
                        "No item exists for item." +
                        inputElement.name +
                        "\n" +
                        "inputElement.name = [" +
                        inputElement.name +
                        "] ";
                        //error.
                        throw error;
                    }
                }
            }
            catch (e)
            {
                console.debug(e);
            }
        });
    }
});